//
//  HMComponseVIewController.swift
//  swift微博项目
//
//  Created by huodian on 16/10/6.
//  Copyright © 2016年 huodian. All rights reserved.
//

import UIKit

import SVProgressHUD

class HMComponseVIewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        setNav()
        setTheTextView()
        
        setNotification()
        
        setToolBar()
        
        settheCollectionView()
        
        self.view.bringSubview(toFront: toolBar)
        
               // Do any additional setup after loading the view.
    }
    //界面从imagepickerController中dismiss时见面发生变化,根据imageArray中数据的变化显示界面
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        
        if selectedAddView.imageArray.count != 0 {
           
         self.selectedAddView.collectionView?.isHidden = false
            
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        textView.resignFirstResponder()
    }
    func setNotification(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(knowThekeyboardChang(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
    }
    
    func knowThekeyboardChang(n:Notification){
        
        let keyBoardfram = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
      let changedY = -screenHeight + keyBoardfram.origin.y
        
        
        toolBar.snp.updateConstraints { (make) in
            
            make.bottom.equalTo(changedY)
            
            //make.bottom.equalTo(changedY)
            //此写法会造成键盘失去第一响应者时bottomtabbar不能回弹到底部
          //  make.bottom.equalTo(self.view.snp.bottom).offset(-keyBoardfram.height)
            
        }
        
        //更新约束后刷新界面才会发生UI的改变,所以对刷新代码进行动画设置一样有效
        UIView.animate(withDuration: 0.5) { 
            self.view.setNeedsLayout()
        }

    }
    

    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    func setNav(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(clickLeftItem))
        
        let titleLable = UILabel(title: "", font: 18, corlor: UIColor.darkGray)
        
          titleLable.textAlignment = .center
        
        let titleText = "发布微博"
        
        
      if  let name  = HMUserAccessViewModel.shareUserAccess.userAccess?.name {
       
      
        
        titleLable.text = "发布微博\n\(name)"
        
        let strM  = NSMutableAttributedString(string: titleLable.text!)
        
        let arrang  = (titleLable.text! as NSString).range(of: name)
        
        strM.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName:UIColor.orange], range: arrang)
        
      
        
        titleLable.attributedText = strM
        }else
      {
        
        titleLable.text = titleText
        
      }
        
          titleLable.sizeToFit()
        
        self.navigationItem.titleView = titleLable
        
        
        self.navigationItem.rightBarButtonItem = rightBtn
        
        
        
        
        
        
        
    }
    func clickRightBtn(){
        
      
            
            let url = "https://api.weibo.com/2/statuses/update.json"
            
            let parameters = ["access_token":HMUserAccessViewModel.shareUserAccess.userAccess?.access_token ?? "","status":textView.text ?? ""]
        
        
        if selectedAddView.imageArray.count == 0 {
            
            HMNetWorking.shareNetWorking.requset(method: .POST, url: url, parameters: parameters) { (_, error) in
                
                if error != nil{
                    
                    SVProgressHUD.showError(withStatus: "请检查网络连接")
                    return
                }
                
                SVProgressHUD.showSuccess(withStatus: "微博发送成功")
                

            
                } } else {
            
            let str = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            HMNetWorking.shareNetWorking.post(str, parameters: parameters, constructingBodyWith: { (formdata) in
                
                let selectedData = UIImagePNGRepresentation(self.selectedAddView.imageArray.last!)
                
                formdata.appendPart(withFileData: selectedData!, name: "pic", fileName: "随便", mimeType: "application/octet-stream")
                
                }, progress: nil, success: { (_, _) in
                    
                    SVProgressHUD.showSuccess(withStatus: "傻缺,你还会发微博,不错呦")
                    
                    
                }, failure: { (_, error) in
                    
                    print(error)
                    
                    SVProgressHUD.showError(withStatus: "大爷的又错了")
                    
            })
            
            
            }
        
        
        }
    
    
    lazy var rightBtn:UIBarButtonItem = {
       
        
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        
        btn.setTitle("发送", for: UIControlState.normal)
        
        btn.setTitleColor(UIColor.darkGray, for: UIControlState.normal)
        
        btn.setTitleColor(UIColor.white, for: UIControlState.disabled)
        
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: UIControlState.normal)
        
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: UIControlState.highlighted)
        
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: UIControlState.disabled)
        
        btn.addTarget(self, action: #selector(clickRightBtn), for: UIControlEvents.touchUpInside)
        
        
        
        let rigthItem = UIBarButtonItem(customView: btn)
        
        rigthItem.isEnabled = false
        
     return rigthItem
        
    }()
    
    
    lazy var textView : UITextView = {
       
        let textView = UITextView()
        
        textView.delegate = self
        
        textView.backgroundColor = UIColor.cyan

        textView.textColor = UIColor.red
        
        textView.font = UIFont.systemFont(ofSize: 14)
        
        textView.alwaysBounceVertical = true
        
        
        return textView
        
        
    }()
    
    lazy  var holderLable = UILabel(title: "千万只草泥马腾空飞过!", font: 14, corlor: UIColor.lightGray)
    
    
    
    
    func setTheTextView(){
        
        self.view.addSubview(textView)
        
        textView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(self.view)
            
            make.height.equalTo(screenHeight / 3)
            
        }
        
      
        
        textView.addSubview(holderLable)
        
        holderLable.snp.makeConstraints { (make) in
            
            make.top.equalTo(textView).offset(7)
            
            make.leading.equalTo(textView).offset(5)
            
        }
        
        
        
        
        
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func clickLeftItem(){
        
        self.dismiss(animated: true, completion: nil)
        
    }
    
    // 设置添加图片
    func settheCollectionView(){
        
       
        
        self.addChildViewController(selectedAddView)
        
        self.view.addSubview(selectedAddView.collectionView!)
        
        selectedAddView.collectionView?.snp.makeConstraints({ (make) in
            
            make.bottom.leading.trailing.equalTo(self.view)
            
            make.height.equalTo(screenHeight / 3 * 2)
        })
        
        
        selectedAddView.collectionView?.isHidden = true
        
        
    }
    
    lazy var keyBoardView:HMInputView = {
        
        let  newView = HMInputView()
        
        newView.frame = CGRect(x: 0, y: 0, width: 0, height: emojiKeyboardHeight)
        
        
        return newView
        
        
        
    }()
    
    lazy var selectedAddView:HMAddImageViewCompone = {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumLineSpacing = margincell
        
        layout.minimumInteritemSpacing = 0
        
        layout.itemSize = CGSize(width: collectionItemW, height: collectionItemW)
        
        layout.sectionInset = UIEdgeInsets(top: margincell, left: margincell, bottom: 0, right: margincell)
        
       let sn = HMAddImageViewCompone(collectionViewLayout: layout)
        
       
        return sn
        
    }()
    
    
    lazy var toolBar : UIToolbar = {
        
        let toolbar = UIToolbar()
        
        var tabbarArray = [UIBarButtonItem]()
        
        let items = ["compose_toolbar_picture",
                      "compose_mentionbutton_background",
                      "compose_trendbutton_background",
                      "compose_emoticonbutton_background",
                      "compose_add_background"]
        
        for item in items.enumerated() {
            
            let btn = UIButton()
            
           btn.setImage(UIImage(named: item.element), for: UIControlState.normal)
           
            btn.setImage(UIImage(named: item.element + "_highlighted"), for: UIControlState.selected)
            
            btn.addTarget(self, action: #selector(clickTabbarItem(item:)), for: UIControlEvents.touchUpInside)
            
            btn.tag = item.offset
            
            btn.sizeToFit()
            
            let toolBaritem = UIBarButtonItem(customView: btn)
            
            tabbarArray.append(toolBaritem)
            
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
            
            tabbarArray.append(space)
            
            
        }

        tabbarArray.removeLast()
        
        toolbar.items = tabbarArray
    
        return toolbar
        
    }()
    
    
    
    
    func clickTabbarItem(item:UITabBarItem){
        
        switch item.tag {
        case 0:
            print("@谁")
            
            selectedAddView.userAddImage()
            
        case 1:
            print("@谁")
        case 2:
            print("@谁")
        case 3:
            
            if !textView.becomeFirstResponder() {
                
                textView.becomeFirstResponder()
                
            }
            
            textView.inputView = (textView.inputView == nil ? keyBoardView : nil)
            
            textView.reloadInputViews()
            
        case 4:
            print("加载更多")
        default:
            print("瞎点啥呀")
        }
        
        
    }
    
    func setToolBar(){
        
        self.view.addSubview(toolBar)
        
        //toolbar不用设置高.有默认值44
        toolBar.snp.makeConstraints { (make ) in
            make.bottom.leading.trailing.equalTo(self.view)
        }
        
    }
    
   }


extension HMComponseVIewController:UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        
        rightBtn.isEnabled = textView.hasText
        
        holderLable.isHidden = textView.hasText
        
        
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        textView.resignFirstResponder()
        
    }
    
}


    
    
    
    
    
    
    



